<?php

namespace app\api\controller\service;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use addons\service\library\WxPay;
use app\api\model\service\UserInfo;
use app\api\model\service\Order;
use app\api\model\service\ProjectConfig;
use fast\Http;
use think\Db;
use fast\Random;
use think\Config;
use think\Cache;
use think\Validate;
class User extends Api
{
    protected $noNeedLogin = ['login', 'logout', 'mobilelogin', 'register', 'resetpwd', 'getNearAddress','changeemail', 'changemobile', 'third', 'phone', 'perfect','cs','userLogin','getLocation','getarea'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }


    public function getNearAddress()
    {
        $name = input('name','');
        $city = input('city','');
        (!$name || !$city) && $this->error('参数缺失');
        $re = \addons\service\library\Common::getAreaList(['city'=>$city,'name'=>$name]);
        $re['status'] == 0 && $this->error('请求失败');
        $this->success('信息返回',$re['pois']);
    }


    public function getArea()
    {
        $data['openCity'] = \app\api\model\service\CityConfig::field('id,city')->order('weigh desc')->select();
        $data['areaList'] = db('area')->where(['level'=>2])->field('id,name,first,lng,lat,pinyin')->select();
        $this->success('信息返回成功',$data);
    }

    /**
     * 根据经纬度获取位置
     * @return void
     */
    public function getLocation()
    {
        $lng = input('lng','');
        $lat = input('lat','');
        (!$lng || !$lat) && $this->error('定位异常');
        $re = \addons\service\library\Map::getLocation($lng,$lat);

        $this->success('地址信息返回成功',$re);
    }


    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户登录
     * @return void
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function userLogin()
    {
        $config = \app\api\model\service\ProjectConfigure::getProjectConfig();
        $type = input('type', '');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (!isset($post['iv'])) {
                $this->error('参数获取异常');
            }
            if (!is_numeric($type)) {
                $this->error('参数缺失');
            }
            switch ($type) {
                case 0:
                    $appid = $config['userappid'];
                    $secret = $config['usersecret'];
                    break;
                case 1:
                    $appid = $config['skillappid'];
                    $secret = $config['skillsecret'];
                    break;
                case 2:
                    $appid = $config['shopappid'];
                    $secret = $config['shopsecret'];
                    break;
                default:
                    $appid = $config['userappid'];
                    $secret = $config['usersecret'];
            }
            $params = [
                'appid' => $appid,
                'secret' => $secret,
                'js_code' => $post['code'],
                'grant_type' => 'authorization_code'
            ];
            $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
            $json = (array)json_decode($result['msg'], true);
            if (array_key_exists('unionid',$json)) {
                $userInfo = \app\api\model\service\UserInfo::get(['unionid' => $json['unionid']]);
            }elseif(array_key_exists('openid',$json)){
                switch ($type)
                {
                    case 0:
                        $userInfo = \app\api\model\service\UserInfo::get(['user_openid' => $json['openid']]);
                        break;
                    case 1:
                        $userInfo = \app\api\model\service\UserInfo::get(['skill_openid' => $json['openid']]);
                        break;
                    case 2:
                        $userInfo = \app\api\model\service\UserInfo::get(['shop_openid' => $json['openid']]);
                        break;
                }
            }else{
                $this->error('登录异常,请联系管理员');
            }
            if ($userInfo) {
                $userInfo->updatetime = time();
                if(!$userInfo->user_openid && $type == 0)
                {
                    $userInfo->user_openid = $json['openid'];
                }elseif (!$userInfo->skill_openid && $type == 1)
                {
                    $userInfo->skill_openid = $json['openid'];
                }elseif (!$userInfo->shop_openid && $type == 2){
                    $userInfo->shop_openid = $json['openid'];
                }
                $userInfo->save();
                $ret = $this->auth->direct($userInfo->user_id);
            } else {
                $errCode = $this->decryptData($appid, $json['session_key'], $this->request->post('encryptedData','', 'trim'), urldecode($this->define_str_replace($post['iv'])), $data);
                if ($errCode == 0) {
                    $data = (array)json_decode($data, true);
                    $mobile = $data['phoneNumber'];
                    $user = \app\common\model\User::getByMobile($mobile);
                    if ($user) {
                        if ($user->status != 'normal') {
                            $this->error(__('Account is locked'));
                        }
                        $userInfo = \app\api\model\service\UserInfo::get(['user_id' => $user->id]);
                        if(array_key_exists('unionid',$json) && $json['unionid'])
                        {
                            $userInfo->unionid = $json['unionid'];
                        }
                        if($userInfo->user_openid != $json['openid']  && $type == 0)
                        {
                            $userInfo->user_openid = $json['openid'];
                        }elseif (!$userInfo->skill_openid != $json['openid'] && $type == 1)
                        {
                            $userInfo->skill_openid = $json['openid'];
                        }elseif (!$userInfo->shop_openid != $json['openid'] && $type == 2){
                            $userInfo->shop_openid = $json['openid'];
                        }
                        $userInfo->save();
                        $ret = $this->auth->direct($user->id);
                    } else {
                        $ret = $this->auth->register($mobile, $mobile, '', $mobile, ['avatar'=>\app\api\model\service\ProjectConfig::getProjectConfig('head_image')]);
                        $uid = $this->auth->id;
                        $newUser = ['user_id'=>$uid,'mobile'=>$mobile];
                        if(array_key_exists('unionid',$json))
                        {
                            $newUser['unionid'] = $json['unionid'];
                        }
                        switch ($type)
                        {
                            case 0:
                                $newUser['user_openid'] = $json['openid'];
                                break;
                            case 1:
                                $newUser['skill_openid'] = $json['openid'];
                                break;
                            case 2:
                                $newUser['shop_openid'] = $json['openid'];
                                break;
                            default:
                                $newUser['user_openid'] = $json['openid'];
                        }
                        $userInfo = new UserInfo($newUser);
                        $userInfo->allowField(true)->save();
                    }
                } else {
                    $this->error('获取信息失败');
                }
                
            }
            if ($ret) {
                    $userInfo = ['user' => $this->auth->getUserinfo(),'userInfo'=>UserInfo::getInfo($this->auth->id)];
                    $this->success(__('Logged in successful'), $userInfo);
            } else {
                    $this->error($this->auth->getError());
            }
        }
        $this->error(__('非法请求'));
    }

    //避免把iv里面的空格转换为 +
    public  function define_str_replace($data)
    {
        return str_replace(' ','+',$data);
    }

    /**
     * 微信信息解密
     * @param $appid
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     * @param $data
     * @return int
     */
    public function decryptData($appid,$sessionKey, $encryptedData, $iv, &$data )
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey=base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return -41003;
        }
        if( $dataObj->watermark->appid != $appid )
        {
            return -41004;
        }
        $data = $result;
        return 0;
    }


}